<template>
  <div>
    <MyTable
      :tableList="tableList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:searchStatus="searchStatus"
      :btnList="['edit', 'delete']"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
      :toolbar="false"
    >
      <template v-slot:tabTop>
        <el-button type="primary" icon="CirclePlusFilled" @click="handleAdd"
          >添加课程</el-button
        >
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      :title="title"
      :formRef="formRef"
      :width="500"
      @confirm="confirm"
      :destroy="true"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        :label-width="120"
        ref="formRef"
        class="wid100"
      >
        <el-form-item label="课程名称" prop="ID_Course">
          <Selector
            category="全部课程"
            @getItem="getCourseItem"
            v-model="formData.ID_Course"
          ></Selector>
        </el-form-item>
        <el-form-item label="总课时" prop="CourseHours">
          <el-input
            v-model="formData.CourseHours"
            v-number="{ args: 'point', dotCount: 2, topNoZero: true }"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="授课教师" prop="ID_Teacher">
          <el-select
            v-model="formData.ID_Teacher"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in teacherList"
              :key="item.ID"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预计开课时间" prop="StartTime">
          <MyDateTime
            :disable="true"
            format="YYYY-MM-DD"
            type="date"
            v-model="formData.StartTime"
            :maxTime="formData.EndTime"
          ></MyDateTime>
        </el-form-item>
        <el-form-item label="预计结课时间" prop="EndTime">
          <MyDateTime
            :disable="true"
            :minTime="formData.StartTime"
            format="YYYY-MM-DD"
            type="date"
            v-model="formData.EndTime"
          ></MyDateTime>
        </el-form-item>
        <el-form-item label="备注" prop="Remark">
          <el-input
            v-model="formData.Remark"
            type="textarea"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-form>
    </MyDialog>
  </div>
</template>

<script setup name="">
import { ref, getCurrentInstance, onMounted } from 'vue';
import {
  DelClassBindCourse,
  AddClassBindCourse,
  EditClassBindCourse,
  GetClassBindCourseList
} from '@/api/school/class.js';
import { GetCourseDetail } from '@/api/lesson/lessonSystem.js';
import useUserStore from '@/store/modules/user.js';
const props = defineProps({
  classID: {
    default: ''
  }
});
const { proxy } = getCurrentInstance();
const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: '序号' },
  { label: '课程名称', prop: 'Name_Course' },
  { label: '总课时', prop: 'CourseHours' },
  { label: '已派课时', prop: 'FinishHours' },
  { label: '授课老师', prop: 'Name_Teacher' },
  { label: '开始时间', prop: 'StartTime' },
  { label: '结束时间', prop: 'EndTime' },
  { label: '备注', prop: 'Remark' },
  // { label: "创建时间", prop: "CreateTime" },
  // { label: "创建人", prop: "CreateUser" },
  { label: '操作', width: 160 }
]);

proxy.$formatKey(columns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10
});
const searchStatus = ref(true);
const queryParams = ref({
  Code: '',
  Name: '',
  NoPage: '' //如果传"true"，则返回全部数据不分页
});
const queryRef = ref();
const show = ref(false);
const title = ref();
const formRef = ref();
const rules = ref({
  ID_Course: [{ required: true, message: '请选择', trigger: 'change' }],
  CourseHours: [{ required: true, message: '请输入', trigger: 'blur' }],
  ID_Teacher: [{ required: true, message: '请选择', trigger: 'change' }],
  StartTime: [{ required: true, message: '请选择', trigger: 'change' }],
  EndTime: [{ required: true, message: '请选择', trigger: 'change' }]
});
const formData = ref({});
const teacherList = ref([]);
onMounted(() => {
  console.log(props.classID);
  getList();
});

async function getList() {
  try {
    let query = {
      ID: props.classID
    };
    console.log(props.classID);
    let res = await GetClassBindCourseList(query);
    res.data?.forEach(item => {
      item.StartTime = item.StartTime.split(' ')[0];
      item.EndTime = item.EndTime.split(' ')[0];
    });
    tableList.value = res.data;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}

async function confirm(val) {
  if (val) {
    try {
      let query = {
        ID_Class: props.classID,
        ...formData.value
      };
      if (query.ID) {
        await EditClassBindCourse(query);
        proxy.$modal.msgSuccess('修改成功');
      } else {
        await AddClassBindCourse(query);
        proxy.$modal.msgSuccess('添加成功');
      }

      show.value = false;
      getList();
    } catch (error) {
      console.log(error);
    }
  }
}

async function handleEdit(row) {
  title.value = '修改课程';
  formData.value = { ...row };
  await getCourseItem({ ID: row.ID_Course }, true);
  show.value = true;
}

async function handleDelete(row) {
  try {
    await DelClassBindCourse({ ID: row.ID });
    proxy.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    console.log(error);
  }
}

async function getCourseItem(item, isEdit = false) {
  if (!item.ID) {
    formData.value.ID_Teacher = '';
    console.log(formData.value);
    teacherList.value = [];
    return;
  }
  if (!isEdit) formData.value.ID_Teacher = '';
  try {
    let res = await GetCourseDetail({ ID: item.ID });
    let list = res.data.BindTeachers?.map(teacher => {
      let obj = useUserStore().allUserList?.find(
        user => teacher.ID_User == user.ID
      );
      return {
        label: obj.Name,
        value: obj.ID
      };
    });
    teacherList.value = list;
  } catch (error) {
    console.log(error);
  }
}

function handleAdd() {
  show.value = true;
  title.value = '添加课程';
  formData.value = {};
  teacherList.value = [];
  console.log(formData.value);
}

function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: '',
    Name: '',
    NoPage: ''
  };
  handleQuery();
}
</script>

<style lang="scss" scoped></style>
